/** \file    convert.cpp
  * \brief   Converts between different image in-memory representations.
  * \date    2001, 2002
  * \author  Fedor Chelnokov
  * \version $Header: /home/cscom1r4/cvsroot/cs/imglib/src/convert.cpp,v 1.1 2004/02/04 14:43:23 cscom1r4 Exp $
  */

#include "imglib/convert.h"
#include "imglib/bitmap.h"
#include "imglib/color.h"
#include "imglib/image.h"
#include "imglib/Arr2Dimg.h"
#include "math/float2int.h"

namespace img {

void share_data( byte_image &img, const AImage &aimg )
{
	img.attach((void*)aimg.begin(), aimg.Width(), aimg.Height());
	assert( img.alignment() <= 1 );
	assert( img.scansize() == img.width()*sizeof(BGRA<unsigned char>) );
}

template <> void copy(FImage & dest, const AImage & source)
{
  if (!YATL::HasEqualDim(source, dest))
    dest.Resize(source.Width(), source.Height());
  std::copy(source.begin(), source.end(), dest.begin());
}

template <> void copy(bitmap & dest, const byte_image & source)
{
	dest.resize(source.width(), source.height());
	byte_image::const_iterator ii;
	bitmap::iterator bi;
	for (ii = source.begin(), bi = dest.begin(); ii != source.end(); ++ii, ++bi) {
		*bi = (*ii).r != 0 || (*ii).g != 0 || (*ii).b != 0;
	}
}

template <> void copy(AImage & dest, const byte_image & source)
{
	AImage source_alias;
	share_data(source_alias, source);
	dest = source_alias;
}

template <> void copy(FImage & dest, const byte_image & source)
{
	AImage a;
	share_data(a, source);
	copy(dest, a);
}

template <> void copy(AImage & dest, const FImage & source)
{
  if (!YATL::HasEqualDim(source, dest))
    dest.Resize(source.Width(), source.Height());
  CFPUmode _m( toNearest ); //round to nearest in subsequent QF2I calls
  for( int i = 0; i != source.Size(); ++i ) {
	  const fRGB &s = source[i];
	  bRGB &d = dest[i];
	  d.r = QF2I( limit(s.r,0.0f,255.0f) );
	  d.g = QF2I( limit(s.g,0.0f,255.0f) );
	  d.b = QF2I( limit(s.b,0.0f,255.0f) );
  }
}

} //namespace img
